package com.cadre.common.utils.oldutil;

import java.math.BigDecimal;
import java.sql.*;
import java.util.*;

/* loaded from: DataSyncUtil.class */
public class DataSyncUtil {
    private HashMap<String, String> tableSqlMap;

    public int dbSync(Connection sqlliteConn, Connection oracleConn, StreamConfig streamconfig, String username, String unitid, Map<String, String> map) throws SQLException {
        this.tableSqlMap = new HashMap<>();
        try {
            selectData(sqlliteConn, oracleConn, streamconfig, username, map, unitid);
            return 1;
        } catch (SQLException e) {
            e.printStackTrace();
            return 1;
        }
    }

    private void selectData(Connection sqlliteConn, Connection oracleConn, StreamConfig streamconfig, String username, Map<String, String> map, String unitid) throws SQLException {
        String[] tableArry = streamconfig.getTables().split(",");
        List<String> list_table_names = new ArrayList<>();
        Collections.addAll(list_table_names, tableArry);
        exitsTable("A01", sqlliteConn, oracleConn, username);
        exitsTable("B01", sqlliteConn, oracleConn, username);
        for (int i = 0; i < list_table_names.size(); i++) {
            exitsTable(list_table_names.get(i), sqlliteConn, oracleConn, username);
        }
        StringBuffer a01WhereStrbuffer = new StringBuffer();
        a01WhereStrbuffer.append(" where A01.flowid in ( ");
        a01WhereStrbuffer.append(" select distinct personid  from A19 where a1915 in ( ");
        a01WhereStrbuffer.append(" select distinct B01.Flowid from B01 start with B01.Flowid= '");
        a01WhereStrbuffer.append(unitid);
        a01WhereStrbuffer.append("' connect by prior B01.Flowid=B01.Parentid");
        a01WhereStrbuffer.append(")");
        a01WhereStrbuffer.append(")");
        if (!map.get("A0181").equals("")) {
            a01WhereStrbuffer.append(" and A0181 ='" + map.get("A0181") + "'");
        }
        if (!map.get("A0179").equals("")) {
            a01WhereStrbuffer.append(" and A0179 ='" + map.get("A0179") + "'");
        }
        if (!map.get("A0198").equals("")) {
            a01WhereStrbuffer.append(" and A0198 ='" + map.get("A0198") + "'");
        }
        List<String> personids = handleData(null, "A01", oracleConn, sqlliteConn, a01WhereStrbuffer.toString());
        a01WhereStrbuffer.delete(0, a01WhereStrbuffer.length());
        a01WhereStrbuffer.append(" where B01.Flowid in (");
        a01WhereStrbuffer.append(" select distinct B01.Flowid from B01 start with B01.Flowid= '");
        a01WhereStrbuffer.append(unitid);
        a01WhereStrbuffer.append("' connect by prior B01.Flowid=B01.Parentid");
        a01WhereStrbuffer.append(")");
        handleData(null, "B01", oracleConn, sqlliteConn, a01WhereStrbuffer.toString());
        if (personids != null && personids.size() > 0) {
            a01WhereStrbuffer.delete(0, a01WhereStrbuffer.length());
            a01WhereStrbuffer.append(" ,(select distinct t.flowid ");
            a01WhereStrbuffer.append("from A01 t, A19 b where  t.flowid= b.personid ");
            a01WhereStrbuffer.append("and b.a1915 in (");
            a01WhereStrbuffer.append(" select distinct B01.Flowid from B01 start with B01.Flowid= '");
            a01WhereStrbuffer.append(unitid);
            a01WhereStrbuffer.append("' connect by prior B01.Flowid=B01.Parentid");
            a01WhereStrbuffer.append(") ");
            if (!map.get("A0181").equals("")) {
                a01WhereStrbuffer.append(" and A0181 ='" + map.get("A0181") + "'");
            }
            if (!map.get("A0179").equals("")) {
                a01WhereStrbuffer.append(" and A0179 ='" + map.get("A0179") + "'");
            }
            if (!map.get("A0198").equals("")) {
                a01WhereStrbuffer.append(" and A0198 ='" + map.get("A0198") + "'");
            }
            a01WhereStrbuffer.append(") f");
            a01WhereStrbuffer.append(" where f.flowid=personid ");
            for (int i2 = 0; i2 < list_table_names.size(); i2++) {
                handleData(null, list_table_names.get(i2), oracleConn, sqlliteConn, a01WhereStrbuffer.toString());
            }
        }
        String[] tableArry_b = streamconfig.getBtables().split(",");
        List<String> list_table_names_b = new ArrayList<>();
        Collections.addAll(list_table_names_b, tableArry_b);
        for (int i3 = 0; i3 < list_table_names_b.size(); i3++) {
            exitsTable(list_table_names_b.get(i3), sqlliteConn, oracleConn, username);
        }
        a01WhereStrbuffer.delete(0, a01WhereStrbuffer.length());
        a01WhereStrbuffer.append(" where Unitid in ( ");
        a01WhereStrbuffer.append(" select distinct B01.Flowid from B01 start with B01.Flowid= '");
        a01WhereStrbuffer.append(unitid);
        a01WhereStrbuffer.append("' connect by prior B01.Flowid=B01.Parentid");
        a01WhereStrbuffer.append(") ");
        for (int i4 = 0; i4 < list_table_names_b.size(); i4++) {
            handleData(null, list_table_names_b.get(i4), oracleConn, sqlliteConn, a01WhereStrbuffer.toString());
        }
        sqlliteConn.close();
        oracleConn.close();
    }

    private List<String> handleData(Statement stmt1, String tableName, Connection oracleConn, Connection sqlliteConn, String whereStr) throws SQLException {
        Map<String, List<HashMap<String, Object>>> totalMap = new HashMap<>();
        List<String> personids = null;
        int FETCH_SIZE = 10000;
        if (tableName.toUpperCase().equals("A01")) {
            personids = new ArrayList<>();
            FETCH_SIZE = 1000;
        }
        String sql = "select  " + tableName + ".* from " + tableName + whereStr;
        String countSQL = "SELECT COUNT(*) as count FROM (" + sql + ")";
        Statement stmt12 = oracleConn.createStatement(1003, 1007);
        stmt12.setFetchSize(FETCH_SIZE);
        stmt12.setFetchDirection(1000);
        stmt12.setQueryTimeout(1200);
        ResultSet rs2 = stmt12.executeQuery(countSQL);
        int count = 0;
        while (rs2.next()) {
            count = rs2.getInt(1);
        }
        ResultSet rs1 = stmt12.executeQuery(sql);
        rs1.setFetchSize(FETCH_SIZE);
        ResultSetMetaData rsm = rs1.getMetaData();
        List<HashMap<String, Object>> rows = new ArrayList<>();
        while (rs1.next()) {
            HashMap<String, Object> row = new HashMap<>();
            for (int j = 1; j <= rsm.getColumnCount(); j++) {
                row.put(rsm.getColumnName(j), rs1.getObject(j));
                if (tableName.toUpperCase().equals("A01") && rsm.getColumnName(j).toUpperCase().equals("FLOWID")) {
                    personids.add(rs1.getObject(j).toString());
                }
            }
            rows.add(row);
            if (rs1.getRow() % FETCH_SIZE == 0) {
                totalMap.put(tableName, rows);
                insertNewDataBase(totalMap, sqlliteConn);
                rows = new ArrayList<>();
                totalMap = new HashMap<>();
            } else if (rs1.getRow() == count) {
                totalMap.put(tableName, rows);
                insertNewDataBase(totalMap, sqlliteConn);
                rows = new ArrayList<>();
                totalMap = new HashMap<>();
            }
        }
        return personids;
    }

    public void insertNewDataBase(Map<String, List<HashMap<String, Object>>> map, Connection conTest) {
        String createTableSql;
        PreparedStatement stmtInsert = null;
        try {
            conTest.setAutoCommit(false);
            int k = 0;
            for (Map.Entry<String, List<HashMap<String, Object>>> elh : map.entrySet()) {
                String key = elh.getKey();
                List<HashMap<String, Object>> lhso = elh.getValue();
                Map<String, Object> cMap = new HashMap<>();
                cMap.put("tablename", key);
                cMap.put("tablename1", key.toLowerCase());
                cMap.put("tablename2", key.toUpperCase());
                if (this.tableSqlMap.get(key) == null) {
                    PreparedStatement pstate2 = conTest.prepareStatement("select sql from sqlite_master where type = 'table' and name in (?,?,?);");
                    pstate2.setString(1, key);
                    pstate2.setString(2, key.toLowerCase());
                    pstate2.setString(3, key.toUpperCase());
                    ResultSet check = pstate2.executeQuery();
                    createTableSql = check.getString(1);
                    while (check.next()) {
                        createTableSql = check.getString(1);
                    }
                    pstate2.close();
                    this.tableSqlMap.put(key, createTableSql);
                } else {
                    createTableSql = this.tableSqlMap.get(key);
                }
                StringBuilder sb = new StringBuilder();
                StringBuilder sbx = new StringBuilder();
                String preSQL = "";
                StringBuilder sb1 = new StringBuilder();
                for (int i = 0; i < lhso.size(); i++) {
                    HashMap<String, Object> mapColumn = lhso.get(i);
                    for (Map.Entry<String, Object> eso : mapColumn.entrySet()) {
                        String cKey = eso.getKey();
                        String cKey1 = eso.getKey().toLowerCase();
                        eso.getKey().toUpperCase();
                        if (createTableSql.contains(cKey) || createTableSql.contains(cKey1) || createTableSql.contains(cKey1)) {
                            sb.append(eso.getKey());
                            sb.append(",");
                            sbx.append("?,");
                        }
                    }
                    sb.deleteCharAt(sb.length() - 1);
                    sbx.deleteCharAt(sbx.length() - 1);
                    String column = sb.toString();
                    String columnx = sbx.toString();
                    if (preSQL.equals("")) {
                        preSQL = "INSERT INTO " + key + "(" + column + ")values (" + columnx + ");";
                    }
                    stmtInsert = conTest.prepareStatement(preSQL);
                    stmtInsert.setQueryTimeout(720);
                    int n = 1;
                    for (Map.Entry<String, Object> eso2 : mapColumn.entrySet()) {
                        String cKey2 = eso2.getKey();
                        String cKey12 = eso2.getKey().toLowerCase();
                        eso2.getKey().toUpperCase();
                        if (createTableSql.contains(cKey2) || createTableSql.contains(cKey12) || createTableSql.contains(cKey12)) {
                            if (eso2.getValue() == null) {
                                stmtInsert.setNull(n, 1);
                                n++;
                            } else if (eso2.getValue().getClass().getName().equals("java.lang.String")) {
                                stmtInsert.setString(n, String.valueOf(eso2.getValue()).replace("'", "").replace("\"", ""));
                                n++;
                            } else if (String.valueOf(eso2.getValue()).contains("oracle.sql.BLOB")) {
                                Blob b = (Blob) eso2.getValue();
                                stmtInsert.setBytes(n, b.getBytes(1, (int) b.length()));
                                n++;
                            } else {
                                stmtInsert.setString(n, String.valueOf(eso2.getValue()));
                                n++;
                            }
                        }
                    }
                    sb1.toString();
                    stmtInsert.execute();
                    k++;
                    sb = sb.delete(0, sb.length());
                    sbx = sbx.delete(0, sbx.length());
                    sb1 = sb1.delete(0, sb1.length());
                }
            }
            conTest.commit();
            stmtInsert.close();
            System.out.println(String.format("同步成功", new Object[0]));
        } catch (Exception e) {
            System.out.println("同步失败");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    public static float bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        filesize.divide(new BigDecimal(1048576), 2, 0).floatValue();
        return filesize.divide(new BigDecimal(1024), 2, 0).floatValue();
    }

    private void exitsTable(String key, Connection conTest, Connection con, String username) throws SQLException {
        Statement stat = conTest.createStatement();
        stat.setQueryTimeout(1200);
        if (conTest.getMetaData().getTables(null, null, key, null).next()) {
            stat.execute("delete from " + key);
            System.out.println(String.format("清空同步库%s表数据", key));
            stat.close();
            return;
        }
        Statement st = con.createStatement();
        st.setQueryTimeout(1200);
        String sereachTableSql = "SELECT DBMS_METADATA.GET_DDL('TABLE','" + key.toUpperCase() + "','" + username.toUpperCase() + "') FROM DUAL";
        ResultSet resultSet = st.executeQuery(sereachTableSql);
        while (resultSet.next()) {
            sereachTableSql = resultSet.getString(1);
        }
        String[] splitStrs = sereachTableSql.replace(", \"", ",").split(", ");
        String newCreateKeys = "";
        for (int i = 0; i < splitStrs.length; i++) {
            String testStr = splitStrs[i].replace("\"", "`");
            if (i == 0) {
                newCreateKeys = newCreateKeys + testStr.substring(testStr.indexOf("(") + 1).replace(" NVARCHAR2", " varchar").replace(" VARCHAR2", " varchar").replace(" NUMBER", " decimal").replace(" DATE", " text").replace(" BLOB", " blob").replace(" ENABLE", "") + ",";
            } else if (testStr.contains("PRIMARY KEY")) {
                newCreateKeys = newCreateKeys + testStr.substring(testStr.indexOf("PRIMARY KEY ("), testStr.indexOf(")") + 1).replace(" NVARCHAR2", " varchar").replace(" VARCHAR2", " varchar").replace(" NUMBER", " decimal").replace(" DATE", " text").replace(" BLOB", " blob").replace(" ENABLE", "").replace("`", "") + ",";
            } else if ((testStr.contains("VARCHAR2") || testStr.contains("NUMBER") || testStr.contains("DATE") || testStr.contains("BLOB")) && !testStr.contains(" ) ")) {
                newCreateKeys = newCreateKeys + testStr.replace(" NVARCHAR2", " varchar").replace(" VARCHAR2", " varchar").replace(" NUMBER", " decimal").replace(" DATE", " text").replace(" BLOB", " blob").replace(" ENABLE", "") + ",";
            } else if ((testStr.contains("VARCHAR2") || testStr.contains("NUMBER") || testStr.contains("DATE") || testStr.contains("BLOB")) && testStr.contains(" ) ")) {
                newCreateKeys = newCreateKeys + testStr.substring(0, testStr.indexOf(" ) ")).replace(" NVARCHAR2", " varchar").replace(" VARCHAR2", " varchar").replace(" NUMBER", " decimal").replace(" DATE", " text").replace(" BLOB", " blob").replace(" ENABLE", "") + ",";
            }
        }
        if (key.toUpperCase().equals("A01") && !newCreateKeys.contains("FOLLOW")) {
            newCreateKeys = " `FOLLOW` decimal(2,0) DEFAULT 0," + newCreateKeys;
        }
        stat.execute("CREATE TABLE `" + key.toUpperCase() + "` (" + newCreateKeys.substring(0, newCreateKeys.length() - 1).replace("*", "20").replace("DEFAULT NULL NOT NULL", "NOT NULL") + ")");
        stat.close();
        st.close();
    }
}
